package com.yxhl.zoume.core.busticket.ui.adapter;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yxhl.zoume.R;
import com.yxhl.zoume.common.adapter.BaseAdapter;
import com.yxhl.zoume.common.ui.custom.RevealLayout;
import com.yxhl.zoume.core.busticket.event.ZMArrivalStationEvent;
import com.yxhl.zoume.core.busticket.event.ZMStartStationEvent;
import com.yxhl.zoume.core.busticket.model.BusSelectCityEntity;
import com.yxhl.zoume.core.busticket.ui.activity.BusStationsListActivity;
import com.yxhl.zoume.core.busticket.ui.info.ZMScheduleType;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.utils.LOG;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;

/**
 * Created by vhawk on 16/3/22.
 */
public class BusArrivalStationAdapter extends BaseAdapter<BaseAdapter.BaseViewHolder> {

    public static final int NOTIFY_ORIGINAL_COUNT = 100;
    private static final String TAG = "BusArrivalStationAdapter";
    private static final int NOTIFY_MORE_COUNT = 100;

    private static final int LETTER_VIEW_TYPE = 1;
    private static final int FOOT_VIEW_TYPE = 2;


    private Context mContext;
    private StationType mStationType;

    private List<BusSelectCityEntity> mTotalBusSelectCityEntityList;
    private List<BusSelectCityEntity> mBusSelectCityEntityList;

    /**
     * 数据集总大小
     */
    private int mTotalSize;

    /**
     * 末尾的插入数据位置
     */
    private int mArrivalInsertPosition;

    private int mScrollDy = 0;
    private FootViewHolder mFootViewHolder;

    private boolean enableLoadMoreData = true;

    public BusArrivalStationAdapter(Context context, List<BusSelectCityEntity> busSelectCityEntityList,
                                    StationType stationType) {
        this.mContext = context;
        this.mStationType = stationType;
        this.mBusSelectCityEntityList = busSelectCityEntityList;
    }

    public void setTotalBusSelectCityEntityList(List<BusSelectCityEntity> totalBusSelectCityEntityList) {
        mTotalBusSelectCityEntityList = new ArrayList<>();
        mTotalBusSelectCityEntityList.addAll(totalBusSelectCityEntityList);
    }

    public void setEnableLoadMoreData(boolean enableLoadMoreData) {
        this.enableLoadMoreData = enableLoadMoreData;
    }

    @Override
    public int getItemCount() {
        return mBusSelectCityEntityList.size();
    }

    @Override
    public int getItemViewType(int position) {
        //是否需要底部Loading布局
        if (enableLoadMoreData) {
            if (mBusSelectCityEntityList != null) {
                int size = mBusSelectCityEntityList.size();
                //城市名搜索时使用
                if (size > 1) {
                    if (position == size - 1) {
                        return FOOT_VIEW_TYPE;
                    }
                }
            }
        }

        if (mBusSelectCityEntityList != null && mBusSelectCityEntityList.size() > 0) {
            BusSelectCityEntity busSelectCityEntity = mBusSelectCityEntityList.get(position);
            String displayContent = busSelectCityEntity.getDisplayContent();
            if (displayContent.matches("[A-Z]{1}")) {
                return LETTER_VIEW_TYPE;
            }
        }
        return super.getItemViewType(position);
    }

    @Override
    public BaseAdapter.BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        switch (viewType) {
            case LETTER_VIEW_TYPE:
                View letterView = layoutInflater.inflate(R.layout.item_bus_station_letter, parent, false);
                return new LetterViewHolder(letterView);
            case FOOT_VIEW_TYPE:
                View view = LayoutInflater.from(mContext).inflate(R.layout.item_recycler_passenger_foot, parent, false);
                mFootViewHolder = new FootViewHolder(view);
                mFootViewHolder.setVisible(false);
                return mFootViewHolder;
            default:
                View stationView = layoutInflater.inflate(R.layout.item_single_textview, parent, false);
                return new StationViewHolder(stationView);
        }
    }

    @Override
    public void onBindViewHolder(BaseAdapter.BaseViewHolder holder, int position) {
        BusSelectCityEntity busSelectCityEntity = mBusSelectCityEntityList.get(position);
        int itemViewType = getItemViewType(position);
        switch (itemViewType) {
            case LETTER_VIEW_TYPE:
                String content = busSelectCityEntity.getDisplayContent();
                LetterViewHolder letterViewHolder = (LetterViewHolder) holder;
                letterViewHolder.setContent(content);
                break;
            case FOOT_VIEW_TYPE:

                break;
            default:
                String displayContent = busSelectCityEntity.getDisplayContent();
                StationViewHolder stationViewHolder = (StationViewHolder) holder;
                stationViewHolder.setContent(displayContent);

        }

    }

    /**
     * 上拉到底部时,加载数据
     */
    public void notifyDataMore() {
        if (mFootViewHolder != null) {
            mFootViewHolder.setVisible(false);
        }

        int beginPosition = mArrivalInsertPosition;
        int notifyCount;

        if (beginPosition + NOTIFY_MORE_COUNT < mTotalSize) {
            notifyCount = NOTIFY_MORE_COUNT;
        } else {
            notifyCount = mTotalSize - beginPosition;
        }
        mArrivalInsertPosition = beginPosition + notifyCount;

        List<BusSelectCityEntity> tempList = new ArrayList<>();
        for (int i = beginPosition; i < mArrivalInsertPosition; i++) {
            tempList.add(mTotalBusSelectCityEntityList.get(i));
        }

        mBusSelectCityEntityList.addAll(mBusSelectCityEntityList.size() - 1, tempList);
        notifyDataSetChanged();
    }

    /**
     * 加载剩余数据
     */
    public void notifyTheRestOfData() {
        int beginPosition = mArrivalInsertPosition;
        int notifyCount = mTotalSize - mArrivalInsertPosition;

        for (int i = beginPosition; i < mTotalSize; i++) {
            mBusSelectCityEntityList.add(mTotalBusSelectCityEntityList.get(i));
        }

        notifyItemRangeInserted(beginPosition, notifyCount);
    }

    /**
     * 一次性更新所有数据
     */
    public void notifyDataAll() {
        //数据清空
        if (mBusSelectCityEntityList.size() > 0) {
            mBusSelectCityEntityList.clear();
            notifyDataSetChanged();
        }

        mTotalSize = mTotalBusSelectCityEntityList.size();
        for (int i = 0; i < mTotalSize; i++) {
            mBusSelectCityEntityList.add(mTotalBusSelectCityEntityList.get(i));
        }

        notifyItemRangeInserted(0, mTotalSize);
    }

    /**
     * 初始化加载数据
     */
    public void notifyDataOriginally(boolean enable) {
        enableLoadMoreData = enable;
        //数据清空
        if (mBusSelectCityEntityList.size() > 0) {
            mBusSelectCityEntityList.clear();
            notifyDataSetChanged();
        }

        mTotalSize = mTotalBusSelectCityEntityList.size();
        int notifyCount;
        if (NOTIFY_ORIGINAL_COUNT < mTotalSize) {
            notifyCount = NOTIFY_ORIGINAL_COUNT;
        } else {
            notifyCount = mTotalSize;
        }
        mArrivalInsertPosition = notifyCount;

        for (int i = 0; i < mArrivalInsertPosition; i++) {
            mBusSelectCityEntityList.add(mTotalBusSelectCityEntityList.get(i));
        }

        mBusSelectCityEntityList.add(new BusSelectCityEntity("", "")); //上拉加载更多loading位置
        notifyItemRangeInserted(0, notifyCount + 1);
    }

    public class ArrivalOnScrollListen extends RecyclerView.OnScrollListener {

        public ArrivalOnScrollListen() {
            super();
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

            switch (newState) {
                case RecyclerView.SCROLL_STATE_SETTLING:
                    break;
                case RecyclerView.SCROLL_STATE_DRAGGING:
                    break;
                case RecyclerView.SCROLL_STATE_IDLE:
                    LOG.e(TAG, "SCROLL_STATE_IDLE");
                    if (mFootViewHolder != null) {
                        if (isCompleteVisibleItem(recyclerView)) {
                            mFootViewHolder.setVisible(true);
                        } else {
                            mFootViewHolder.setVisible(false);
                        }
                    }
                    break;
            }

        }

        private boolean isCompleteVisibleItem(RecyclerView recyclerView) {
            if (enableLoadMoreData) {
                if (mScrollDy > 0) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                    int currentSize = mBusSelectCityEntityList.size();
                    LOG.e(TAG, "lastVisibleItemPosition=" + lastVisibleItemPosition + "  currentSize=" + currentSize);
                    if (lastVisibleItemPosition >= currentSize - 1 && currentSize < mTotalSize) {
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mScrollDy = dy;
        }
    }

    class StationViewHolder extends BaseAdapter.BaseViewHolder {
        @BindView(R.id.tv_item)
        TextView itemTv;
        @BindView(R.id.ll_item)
        RevealLayout itemParent;

        public StationViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void setContent(String str) {
            if (str != null) {
                itemTv.setText(str);
            }
        }

        @OnClick(R.id.ll_item)
        public void onItemClick() {
            BusSelectCityEntity busSelectCityEntity = mBusSelectCityEntityList.get(getLayoutPosition());
            if (busSelectCityEntity != null) {
                String cityName = busSelectCityEntity.getDisplayContent();
                String cityCode = busSelectCityEntity.getCityCode();
                List<ZMScheduleType> scheduleTypeList = busSelectCityEntity.getScheduleTypeList();

                if (StationType.STATION_TYPE_START == mStationType) {
                    if (!TextUtils.isEmpty(cityCode)) {
                        RxBus.getInstance().send(new ZMStartStationEvent(cityCode, cityName));
                    }
                } else {
                    if (!TextUtils.isEmpty(cityCode)) {
                        RxBus.getInstance().send(new ZMArrivalStationEvent(cityCode, cityName, scheduleTypeList));
                    }
                }

                ((BusStationsListActivity) mContext).finish();
            }
        }
    }

    class LetterViewHolder extends BaseAdapter.BaseViewHolder {

        @BindView(R.id.tv_item_bus_station_letter)
        TextView letterTv;

        public LetterViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        void setContent(String str) {
            if (str != null) {
                letterTv.setText(str);
            }
        }
    }

    class FootViewHolder extends BaseAdapter.BaseViewHolder {

        public static final int UP_PULL_REFRESH_DELAY = 500;

        @BindView(R.id.rl_up_pull_foot_container)
        RelativeLayout relativeLayout;

        @BindView(R.id.bar_up_pull_foot)
        MaterialProgressBar upPullFootBar;

        public FootViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(FootViewHolder.this, itemView);
        }

        void setVisible(boolean enableVisible) {
            LOG.e(TAG, "enableVisible=" + enableVisible);
            if (enableVisible) {
                relativeLayout.setVisibility(View.VISIBLE);
                relativeLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //加载并更新数据
                        notifyDataMore();
                    }
                }, UP_PULL_REFRESH_DELAY);

            } else {
                relativeLayout.setVisibility(View.INVISIBLE);
            }
        }

    }

}
